package com.cmy.framework.mvvm.mvvm.view_model

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.cmy.framework.mvvm.event.UIChangeLiveData
import com.cmy.framework.mvvm.mvvm.view.BaseActivity
import com.cmy.framework_base.common.UiState
import com.cmy.framework_utils.JumpPageUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch

/**
 * @name:
 *  BaseViewModel
 * @package:
 *  com.cmy.framework.mvvm.binding
 * @date:
 *  2023/2/1615:29
 * @author
 *    cmy
 * @description
 *
 */
open class BaseViewModel : ViewModel(), LifecycleObserver {

    /**
     * 状态监听代码，监听当前数据状态
     */
    val uiState = MutableStateFlow(UiState.LoadDefault)


    val handlerCode = MutableLiveData<Int>()

    /**
     * UI刷新需要的拓展交互
     */
    val uiChange : UIChangeLiveData by lazy { UIChangeLiveData() }

    
    /**
     * 运行在IO线程的协程，作用域数据网络请求 viewModelScope 已经实现了在onCleared取消协程
     */
    fun launchIO(block: suspend CoroutineScope.() -> Unit) = viewModelScope.launch (Dispatchers.IO){  block() }

    /**
     * 运行在UI线程的协程， viewModelScope 已经实现了在onCleared取消协程
     */
    fun launchUI(block: suspend CoroutineScope.() -> Unit) = viewModelScope.launch (Dispatchers.Main){  block() }

    /**
     * 默认格式
     */
    fun launch(block: suspend CoroutineScope.() -> Unit) = viewModelScope.launch{  block() }


    /**
     * 关闭页面处理
     */
    protected fun finish(){
        uiChange.finishEvent.call()
    }


    /**
     * 跳转页面
     *
     * @param context   环境变量
     * @param block Bundle对应的函数信息
     */
    inline fun <reified T : BaseActivity>  startActivityBundle(context: Context, block: Bundle.() -> Unit) {
        JumpPageUtils.startActivityBundle<T>(context,block)
    }


    /**
     * 跳转页面
     *
     * @param context 环境变量
     * @param block Intent对应的数据函数
     */
    inline fun <reified T : BaseActivity>  startActivity(context: Context, block: Intent.() -> Unit) {
        JumpPageUtils.startActivity<T>(context,block)
    }
}